package es.abredatos.client.presenter;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

import es.abredatos.client.BooksLocatorServiceAsync;
import es.abredatos.client.event.SearchBookEvent;

public class HomePresenter implements Presenter {

	public interface Display {
		HasValue<String> getInput();

		HasClickHandlers getSearchButton();
	}

	private BooksLocatorServiceAsync rpcService;
	private HandlerManager eventBus;
	private Display display;

	public HomePresenter(BooksLocatorServiceAsync rpcService, HandlerManager eventBus, Display display) {
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.display = display;
	}

	public void go(HasWidgets container) {
		container.clear();
		container.add((Widget) display);

		bind();
	}

	private void bind() {
		display.getSearchButton().addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent event) {

				final String query = display.getInput().getValue();
				if (!"".equals(query)) {
					eventBus.fireEvent(new SearchBookEvent(query));
				}
			}
		});
	}

}
